<template>
    <div class="app-container">
        <el-card class="export-card">
            <el-form ref="FormRef" :model="FilePathObj" label-width="100px" :rules="Rules">
                <el-tabs v-model="tabActive" class="demo-tabs" @tab-click="handleTabClick">
                    <el-tab-pane label="扫描" :name="1">
                        <el-form-item label="选择存储位置" class="form-grid" prop="cabientActive" >
                            <div v-loading="CabientLoad" style="min-height: 50px;">
                                <div class="grid-row" v-for="(item, index) in cabientList" :key="index">
                                    <div class="grid-col col-1" >
                                        {{ item.name}}
                                    </div>
                                    <div class="grid-col" :class="{'active':cabientActive.includes(citem),'gridDisable':citem.disable == 1 }" v-for="(citem,cindex) in item.doors" :key="cindex" @click="gridActive(citem,cindex)">
                                        {{ citem.cabinetId +','+ citem.name }}
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="创建存储位置"></el-form-item>
                        <el-form-item>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="文件柜" label-width="80px" prop="cabinet">
                                        <div class="flex">
                                            <el-input-number 
                                                v-model="FilePathObj.cabinet" 
                                                :precision="0" 
                                                :min="1" 
                                                :max="100" 
                                                style="width: 120px;"
                                                controls-position="right"
                                                placeholder="请输入"
                                            ></el-input-number>
                                            &nbsp;<span>号</span>
                                        </div>
                                    </el-form-item>
                                </el-col>
                                
                                <el-col :span="24" style="margin-top: 20px;">
                                    <el-form-item label="柜门" label-width="80px" prop="cabinetdoor">
                                        <div class="flex">
                                            <el-input-number 
                                                v-model="FilePathObj.cabinetdoor" 
                                                :precision="0" 
                                                :min="1" 
                                                :max="100" 
                                                style="width: 120px;"
                                                controls-position="right"
                                                placeholder="请输入"
                                            ></el-input-number>
                                            &nbsp;<span>号</span>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <div class="" style="width: 600px;text-align: center;margin-top: 50px;">
                            <el-button type="primary"  :loading="scanLoading" @click="startScan">开始扫描</el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="OCR识别" :name="2">
                        <template v-if="tabActive == 2">
                            <el-form-item label="待处理任务：" label-width="120px">
                                <el-row style="width: 100%;margin-top: 30px;">
                                    <el-col :span="6">
                                        <div class="flex">
                                            <span>任务：</span>
                                            <span style="margin-left: 10px;">
                                                {{ taskNum || '--'}} 条
                                            </span>
                                        </div>
                                    </el-col>
                                    <el-col :span="6">
                                        <div class="flex">
                                            <span>页面：</span>
                                            <span style="margin-left: 10px;">
                                                {{ taskPageNum || '--' }} 条
                                            </span>
                                        </div>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <!-- <el-form-item label="处理进度：" label-width="auto"></el-form-item> -->
                            <!-- <div class="progress-container" v-if="StartType"> -->
                                <!-- <span>处理进度：</span> -->
                                <!-- <el-progress :percentage="ProgressNum" >
                                    <div >
                                        {{(ProgressObj?.progress || 0) +'/' + (ProgressObj.all || 0)}}
                                    </div>
                                </el-progress> -->
                            <!-- </div> -->
                            <div style="margin-top: 30px;"></div>
                            <el-table :data="TableData" style="width: 100%" height="64vh" v-loading="loading" >
                                <el-table-column prop="cabinet" label="存储位置" min-width="200"  >
                                    <template #default="scope">
                                        {{ scope.row.cabinetId ? scope.row.cabinetId + ',' + scope.row.name : '--' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="pageCount" label="页面(页)" min-width="120"></el-table-column>
                                <el-table-column prop="contractCount" label="文档" min-width="180"/>
                                <el-table-column prop="useSeconds" label="用时" min-width="180">
                                    <template #default="scope">
                                        <el-progress :percentage="scope.row.ProgressNum" v-if="scope.row.loading" >
                                            <div >
                                                {{(scope.row?.progress || 0) +'/' + (scope.row.all || 0)}}
                                            </div>
                                        </el-progress>
                                        <div v-else>
                                            {{ scope.row.useSeconds || '--'  }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column  label="完成时间" min-width="200">
                                    <template #default="scope">
                                        {{scope.row.finishTime?moment(scope.row.finishTime).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                                    </template>
                                </el-table-column>
                                <el-table-column  label="OCR识别" width="120" fixed="right">
                                    <template #default="scope">
                                        <el-button type="text" v-if="scope.row.state == 'SCANFish'" :loading="scope.row.loading" @click="Starthandle(scope.row)" >{{ '开始处理'}}</el-button>
                                        <span type="text" v-else >{{status[scope.row.state]}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-tab-pane>
                    <el-tab-pane label="提取信息" :name="3">
                        <template v-if="tabActive == 3">
                            <el-form-item label="待处理任务：" label-width="120px">
                                <el-row style="width: 100%;margin-top: 30px;">
                                    <el-col :span="6">
                                        <div class="flex">
                                            <span>任务：</span>
                                            <span style="margin-left: 10px;">
                                                {{ taskNum || '--'}} 条
                                            </span>
                                        </div>
                                    </el-col>
                                    <el-col :span="6">
                                        <div class="flex">
                                            <span>文档：</span>
                                            <span style="margin-left: 10px;">
                                                {{ taskPageNum || '--' }} 份
                                            </span>
                                        </div>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <!-- <el-form-item label="处理进度：" label-width="auto"></el-form-item> -->
                            <!-- <div class="progress-container" v-if="StartType">
                                <span>处理进度：</span> -->
                                <!-- <el-progress :percentage="ProgressNum" >
                                    <div >
                                        {{(ProgressObj?.progress || 0) +'/' + (ProgressObj.all || 0)}}
                                    </div>
                                </el-progress> -->
                            <!-- </div> -->
                            <div style="margin-top: 30px;"></div>
                            <el-table :data="TableDataTwo" style="width: 100%" height="64vh" v-loading="loading" >
                                <el-table-column type="expand">
                                    <template #default="scope" >
                                        <div v-if="scope.row.contacts && scope.row.contacts.length > 0">
                                            <el-table :data="scope.row.contacts" style="width: 100%" >
                                                <el-table-column prop="title" label="合同名称" min-width="180"/>
                                                <el-table-column label="操作" width="180">
                                                    <template #default="scope">
                                                        <el-button type="text" @click="handleDownLoad(scope.row)" >详情</el-button>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                        <div align="center" v-else>数据未处理完成，请稍后重试</div>
                                    </template>                                    
                                </el-table-column>
                                <el-table-column prop="cabinet" label="存储位置" min-width="200"  >
                                    <template #default="scope">
                                        {{ scope.row.cabinetId ? scope.row.cabinetId + ',' + scope.row.name : '--' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="pageCount" label="页面(页)" min-width="120"></el-table-column>
                                <el-table-column prop="contractCount" label="文档" min-width="180"/>
                                <el-table-column prop="useSeconds" label="用时" min-width="180">
                                    <template #default="scope">
                                        <!-- {{ scope.row }} -->
                                        <el-progress :percentage="scope.row.ProgressNum" v-if="scope.row.loading" >
                                            <div >
                                                {{(scope.row?.progress || 0) +'/' + (scope.row.all || 0)}}
                                            </div>
                                        </el-progress>
                                        <div v-else>
                                            {{ scope.row.useSeconds || '--'  }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column  label="完成时间" min-width="200">
                                    <template #default="scope">
                                        {{scope.row.finishTime?moment(scope.row.finishTime).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                                    </template>
                                </el-table-column>
                                <el-table-column  label="提取关键信息" width="160" fixed="right">
                                    <template #default="scope">
                                        <el-button type="text" :loading="scope.row.loading" v-if="scope.row.state == 'OCRSuccess'" @click="Starthandle(scope.row)" >开始提取</el-button>
                                        <span type="text" v-else >{{status[scope.row.state]}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

            <!-- <el-row :gutter="20">
                <el-col :span="8">
                    <el-input v-model="FilePath" :readonly="StartType" placeholder="请输入文件路径"></el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" :disabled="!FilePath" :loading="StartType" @click="startProcessClick">开始处理</el-button>
                    <el-button type="primary" @click="getFileList">刷新</el-button>
                </el-col>
            </el-row>
            <div class="progress-container" v-if="StartType">
                <span>处理进度：</span>
                <el-progress :percentage="ProgressNum" >
                    <div >
                        {{(ProgressObj?.progress || 0) +'/' + (ProgressObj.all || 0)}}
                    </div>
                </el-progress>
            </div>
            <div style="margin-top: 30px;"></div>
            <el-table :data="TableData" style="width: 100%" height="80vh" v-loading="loading">
                <el-table-column prop="obj" label="文件路径" min-width="180"/>
                <el-table-column prop="stateStr" label="任务状态" min-width="120"></el-table-column>
                <el-table-column prop="ct" label="开始时间" min-width="200">
                    <template #default="scope">
                        {{scope.row.ct?moment(scope.row.ct).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="oft" label="处理完成" min-width="200">
                    <template #default="scope">
                        {{scope.row.oft?moment(scope.row.oft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="ft" label="完成时间" min-width="200">
                    <template #default="scope">
                        {{scope.row.ft?moment(scope.row.ft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="cabinet" label="存储位置" min-width="200" show-overflow-tooltip />
                <el-table-column  label="操作" width="120">
                    <template #default="scope">
                        <el-button type="text" @click="handleDownLoad(scope.row)" >详情</el-button>
                    </template>
                </el-table-column>
            </el-table> -->
        </el-card>
        <el-dialog :title="'详情'" v-model="dialogVisible" width="800px" :before-close="handleClose">
            <el-form :model="dialogData" label-width="100px" v-loading="dialogload">
                <el-form-item label="文件路径">
                    {{ dialogData.obj }}
                </el-form-item>
                <el-form-item label="任务状态">
                    {{ dialogData.stateStr }}
                </el-form-item>
                <el-form-item label="开始时间">
                    {{dialogData.ct?moment(dialogData.ct).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                </el-form-item>
                <el-form-item label="处理完成">
                    {{dialogData.oft?moment(dialogData.oft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                </el-form-item>
                <el-form-item label="完成时间">
                    {{dialogData.ft?moment(dialogData.ft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                </el-form-item>
                <el-form-item label="存储位置">
                    {{ dialogData.cabinet }}
                </el-form-item>
                <el-form-item label="合同数">
                    {{ dialogData.count }}
                </el-form-item>
                <el-form-item label="合同">
                    <el-table :data="dialogTable" border style="width: 100%"  >
                        <el-table-column prop="title" label="合同名称" min-width="180"/>
                        <el-table-column prop="page" label="页数" min-width="180"/>
                        <el-table-column prop="stateStr" label="状态" min-width="180"/>
                    </el-table>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';    // 导入 ElMessage
import axios from 'axios';
import moment from 'moment';
import { CabientQuery, CabinetScan, CabinetTaskQuery, CabinetTaskStart, CabinetTaskProgress  } from "@/api/user";


const loading = ref(false);
const dialogload = ref(false);
const dialogVisible = ref(false);
const CabientLoad = ref(false);
const InputRef = ref(null);
const StartType = ref(false);
const taskNum = ref(0);
const taskPageNum = ref(0);
const files = ref([]);
const scanLoading = ref(false);
const FormRef = ref(null);
const dialogTable = ref([]);
const cabientList = ref([]);
const cabientActive = ref([]);
const FilePath = ref('');
const TableData = ref([]);
const TableDataTwo = ref([]);
const ProgressNum = ref(0);
const dialogData = ref({});
const tabActive = ref(1);
const ProgressObj = ref({
    
});
const status = {
    'SCANPending': '待SCAN',
    'SCANFish': 'SCAN完成',
    'OCRPending': 'OCR待处理',
    'OCRProcessing': 'OCR处理中',
    'OCRSuccess': 'OCR成功',
    'AIPending': 'AI待处理',
    'AIProcessing': 'AI处理中',
    'SUCCESS': '成功',
    'Failed': '处理失败',
    'unkonwn': '未知状态',
};
const Rules = computed(()=>({
    cabinet:[
        {required:cabientActive.value.length == 0,message:'请输入文件柜号',trigger:'blur'},
        {
            validator: (rule, value, callback) => {
                if ((cabientActive.value.length == 0 && !value) || (FilePathObj.value.cabinetdoor && !value)) {
                    callback(new Error('请输入文件柜号'));
                }
                callback();
            }
        }
    ],
    cabinetdoor:[
        {required:cabientActive.value.length == 0,message:'请输入柜门号',trigger:'blur'},
        {
            validator: (rule, value, callback) => {
                if ((cabientActive.value.length == 0 && !value) || (FilePathObj.value.cabinet && !value)) {
                    callback(new Error('请输入柜门号'));
                }
                callback();
            }
        }
    ],
    cabientActive:[

    ]
}))
const FilePathObj = ref({})

const handleTabClick = (tab) => {
    tabActive.value = tab.props.name;
    if(tab.props.name == 2 || tab.props.name == 3){
        startProcessClick();
    }
}

const handleDownLoad = (row) => {
    // downloadFile(path);
        // window.open('http://localhost:10899/file/download?fileId='+row.fileId);
    // dialogVisible.value = true;
    // getExportInfo(row)
    window.open('http://localhost:10899/file/download?fileId='+row.fileId);

}


onMounted(() => {
    // if(localStorage.getItem('GroupId')){
    //     StartType.value = true;
    //     getProgress();
    // }else{
    //     getFileList();
    // }
    if(tabActive.value == 1){
        getCabinetData();
    }
});
const gridActive = (item, cindex) => {
    if(item.disable == 1){
       return; 
    }
    if(!cabientActive.value.includes(item)){
        cabientActive.value.push(item);
    }else{
        cabientActive.value = cabientActive.value.filter(i => i != item);
    }
}
const getCabinetData = async () => {
    CabientLoad.value = true;
    let result = await CabientQuery();
    CabientLoad.value = false;
    if(result.errorCode == 0){
        cabientList.value = result.data;
    }else{
        cabientList.value = [];
        ElMessage.error(result.errorMsg);
    }
}

const Starthandle = async (row)=>{
    // 这里可以添加OCR识别的具体逻辑
    if(row.state == 'SCANFish'){
        ElMessage.success('开始OCR识别');
        // 开始处理
        row.loading = true;
        // 处理逻辑
        let result = await CabinetTaskStart({
            doorId:row.id
        })
        await getProgress(row);
    }
    if(row.state == 'OCRSuccess'){
        ElMessage.success('开始信息提取');
        row.loading = true;
        // 处理逻辑
        let result = await CabinetTaskStart({
            doorId:row.id
        })
        await getProgress(row);
    }
}


const startScan = () => {
    FormRef.value.validate(async(valid) => {
        if (valid) {
            scanLoading.value = true;
            let actives = [];
            if(cabientActive.value.length != 0){
                for (let i = 0; i < cabientActive.value.length; i++) {
                    const it = cabientActive.value[i];
                    actives.push({
                        cabinet:it.cabinetId,
                        door:it.name,
                    })
                }
            }
            if(FilePathObj.value.cabinet && FilePathObj.value.cabinetdoor){                
                actives.push({
                    cabinet: FilePathObj.value.cabinet,
                    door: FilePathObj.value.cabinetdoor,
                });
            }
            let result = await CabinetScan({doors:actives});
            scanLoading.value = false;
            if(result.errorCode == 0){
                ElMessage.success('扫描成功');
                FilePath.value = result.data;
                cabientActive.value = [];
                localStorage.setItem('GroupId', result.data);
                FilePathObj.value = {
                    cabinet: '',
                    cabinetdoor: '',
                };
                tabActive.value = 2;
                startProcessClick()
            }
        }
    })
}
const handleClose = () => {
    dialogData.value = {};
    dialogVisible.value = false;
}
const getExportInfo = (row) => {
    dialogload.value = true;
    axios({
        method: 'post',
        url: import.meta.env.VITE_Request_Path+'/task/get',
        data: {
            id: row.id,
        },
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        },
    }).then(res => {
        if(res.data.errorCode == 0){
            dialogData.value = res.data.data;
            dialogTable.value = res.data.data?.items;
        }else{
            dialogData.value = {};
            dialogTable.value = [];
            ElMessage.error(res.data.errorMsg);
        }
    }).catch(err => {
        ElMessage.error('获取合同详细失败!');
    }).finally(() => dialogload.value = false);
}

// 创建一个a标签，并做下载点击事件
const downloadFile = (str, fileName) => {
    const link = document.createElement("a");
    link.href = str;
    // link.download = fileName;
    // 此写法兼容可火狐浏览器
    document.body.appendChild(link);
    const evt = document.createEvent("MouseEvents");
    evt.initEvent("click", false, false);
    link.dispatchEvent(evt);
    document.body.removeChild(link);
}

const startProcessClick = async () => {
    StartType.value = true;
    // axios.defaults.withCredentials = true;
    ElLoading.service({
        lock: true,
        text: 'Loading...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    console.log(tabActive.value);
    
    let result = await CabinetTaskQuery({
        taskId: localStorage.getItem('GroupId'),
        type: tabActive.value == 2 ? 'ocr' : tabActive.value == 3 ?'ai':'',
    })
    ElLoading.service().close();
    StartType.value = false;
    if (result.errorCode == 0) {
        // 这里可以添加处理逻辑
        localStorage.setItem('FilePath', FilePath.value);
        // ElMessage.success('文件提取完成，正在处理文件，请稍等...');
        // taskPageNum.value = 1;
        if(tabActive.value == 2){
            TableData.value = result.data;
        }else{
            TableDataTwo.value = result.data;
        }
        taskNum.value = result.data.length;
        if(tabActive.value == 2){
            taskPageNum.value = result.data.reduce((acc, item) => acc + (item.pageCount || 0), 0);
        }else if(tabActive.value == 3){
            taskPageNum.value = result.data.reduce((acc, item) => acc + (item.contractCount || 0), 0);
        }
    }else{
        TableData.value = [];
        TableDataTwo.value = result.data;
        ElMessage.error(result.errorMsg);
    }
};
const getProgress = async (row) => {
    // axios.defaults.withCredentials = true;
    let res = await CabinetTaskProgress({
        doorId: row.id 
    })
    if(res.errorCode == 0){
        row.ProgressNum =  res.data.all == 0 ? 0 : ((res.data.progress / res.data.all).toFixed(4) * 100).toFixed(2);
        row.progress = res.data.progress;
        row.all = res.data.all;
        if(res.data.progress == res.data.all && res.data.all != 0){
            StartType.value = false;
            FilePath.value = '';
            ElMessage.success(tabActive.value == 2 ? 'OCR识别完成!':'信息提取完成!');
            row.loading = false;
            startProcessClick();
            localStorage.removeItem('GroupId');
            localStorage.removeItem('FilePath');
        }else{
            setTimeout(async () => {
                if(res.data.all != 0){
                    if(!StartType.value){
                        StartType.value = true;
                        FilePath.value = localStorage.getItem('FilePath');
                    }
                    if(tabActive.value == 2 || tabActive.value == 3){
                        await getProgress(row);
                    }
                }else{
                    StartType.value = false;
                    ElMessage.warning(tabActive.value == 2 ? 'OCR识别进度异常！':'信息提取进度异常！');
                    // localStorage.removeItem('GroupId');
                }
                // await startProcessClick();
            }, 1500);
        }
    }else{
        StartType.value = false;
        ElMessage.error(res.data.errorMsg);
        // localStorage.removeItem('GroupId');
        // localStorage.removeItem('FilePath');
    }
  
}
</script>

<style scoped lang="scss">
.file-input {
    display: none;
    opacity: 0;
}
.export-card{
    // padding-top: 15px;
    .progress-container{
        margin: 30px 0;
        display: flex;
        align-items: center;
        .el-progress{
            flex: 1;
        }
    }
    :deep(.form-grid){
        .el-form-item__content{
            display: block;
            .grid-row{
                display: flex;
                .grid-col{
                    width: 40px;
                    height: 40px;
                    border: 1px solid #ccc;
                    line-height: 40px;
                    text-align: center;
                    &+.grid-col{
                        font-weight: bold;
                        cursor: pointer;
                        border-left: 0;
                    }
                    &.active{
                        background: #409eff;
                        color: #fff;
                    }
                    &.gridDisable{
                        background: #ccc;
                        color: #fff;
                        cursor: not-allowed;
                    }
                }
                .col-1{
                    background: #71b8ff;
                    color: #fff;
                }
            }
        }
    }
}
</style>